package com.example.audio_test.ui

import android.hardware.Camera
import android.media.CamcorderProfile
import android.media.MediaRecorder
import android.os.Environment
import android.view.SurfaceHolder
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.audio_test.R
import com.kun.base.ui.AbsBaseActivity
import kotlinx.android.synthetic.main.activity_media_recorder.*
import java.io.File

/**
 *mediaRecorder 视频录制
 *
 * @author : Kun
 * @date : 2021/6/25
 * @time : 9:46
 */
@Route(path = "/recordTest/MediaRecorderActivity")
class MediaRecorderActivity : AbsBaseActivity(), SurfaceHolder.Callback {
    private var camera: Camera? = null

    private var mediaRecorder: MediaRecorder? = null


    override fun getLayoutId(): Int {
        return R.layout.activity_media_recorder
    }

    override fun initViewModel() {
    }

    override fun initView() {
        surface_view.holder.addCallback(this)

        btn_start.setOnClickListener {
            startRecord()
        }

        btn_end.setOnClickListener {
            stopVideoRecord()
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        if (camera == null) {
            camera = Camera.open()
        }
        camera!!.enableShutterSound(false)
        camera!!.setDisplayOrientation(90)
        camera!!.setPreviewDisplay(holder)
        camera!!.startPreview()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        if (holder.surface == null) {
            return
        }
        camera!!.stopPreview()
        camera!!.setPreviewDisplay(holder)
        camera!!.startPreview()
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }

    private fun startRecord() {
        mediaRecorder = MediaRecorder().apply {
            camera!!.unlock()
            setCamera(camera)
            setOrientationHint(90)

            setAudioSource(MediaRecorder.AudioSource.CAMCORDER)
            setVideoSource(MediaRecorder.VideoSource.CAMERA)

            // 输出的视频格式
            setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)

            setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH))

            val file = File(getExternalFilesDir(Environment.DIRECTORY_MOVIES), "test.mp4")
            if (file.exists()) {
                file.delete()
            }
            setOutputFile(file.absolutePath)

            setPreviewDisplay(surface_view.holder.surface)
            prepare()
            start()
        }

    }


    private fun stopVideoRecord() {
        mediaRecorder?.let {
            it.stop()
            it.release()
            mediaRecorder = null
        }
        camera!!.lock()
    }

}